package org.brisling.medical.queryService;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.servlet.http.HttpSession;

import org.brisling.base.domain.ChartDomain;
import org.brisling.base.domain.ListDomain;
import org.brisling.base.service.AbstractBaseQueryService;
import org.brisling.common.ConstSysParam;
import org.brisling.common.SysConfig;
import org.brisling.common.exception.DangerousOperatorException;
import org.brisling.common.util.DateUtil;
import org.brisling.common.util.LongUtil;
import org.brisling.common.util.StringUtil;
import org.brisling.medical.domain.MedicalBizStatistic;
import org.brisling.medical.domain.MedicalInpatient;
import org.brisling.medical.domain.MedicalRecipel;
import org.brisling.medical.domain.MedicalStatistic;
import org.brisling.sysman.queryService.QueryDictionaryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

/**
 * 
 * <p>Title: QueryMedicalstatisticService</p>
 * <p>Description: 医疗服务统计信息查询service</p>
 * <p>Company: tongking</p>
 * @author peter fan
 * @since 1.0
 * @version 1.0
 * @date 2016年7月20日 下午10:08:58
 */
@RestController
@RequestMapping("/medicalStatistic/query")
public class QueryMedicalstatisticService extends AbstractBaseQueryService<MedicalStatistic>{
	
	
	@Autowired
	private QueryDictionaryService dicService;
	
	@Autowired
	private QueryInpatientService inService;
	
	@Autowired
	private QueryRecipelService recipelService;
	
	public QueryMedicalstatisticService(){
		this.moduleName = ConstSysParam.MODULE_MEDICAL_STATISTIC;
		this.subSystem = ConstSysParam.SUBSYSTEM_MEDICAL;
		this.tableName = ConstSysParam.VIEW_MEDICAL_STATISTIC;
		this.clazz = MedicalStatistic.class;
		
		typeMap = this.getTypeMap(MedicalRecipel.class);
		
		orderMap.put("sumary_matter", "desc");
		
	}
	
	@PersistenceContext(unitName=ConstSysParam.SUBSYSTEM_SYSMAN)
	@Autowired
	protected void setEntityManager(EntityManager entityManager){
		this.entityManager = entityManager;		
	}
	
	@RequestMapping("/mainPage.action")
	public ModelAndView getMainPage(){
		return this.getBizMainPage();
	}
	
	/* (non-Javadoc)
	 * @see org.brisling.service.sysman.DepartmentServiceInf#getEditPage()
	 */
	@RequestMapping("/editPage.action")
	public ModelAndView getEditPage(){
		return this.getBizEditPage();
	}	
	
	@RequestMapping("/bizStatisticPage.action")
	public ModelAndView getBizStatisticPage(){
		return new ModelAndView("/medical/medical_statistic/bizMain");
	}
	
	@RequestMapping("/getInquiryStatisticListDomain.action")
	public ListDomain<Object> getInquiryStatisticListDomain(@RequestBody(required=false) String body,HttpSession session){
		String sql = dicService.getSqlByBizcode("medical_inquiry_statistic");
		String userid = getUserid(session);
		Map<String,Object> conditionMap = this.getBodyParam(body);
		
		String whereCorse = "";
		if(!this.isSuperDept(userid,ConstSysParam.QUERY_ALL, "query_medical_all")){
			whereCorse = String.format(" where doct_depart_code = '%1$s'", SysConfig.getUsr(userid).getDeptid().toString());
		}
			
		sql = String.format(sql, whereCorse);
		return super.getPagedClassListDomain(sql, conditionMap,MedicalRecipel.class,MedicalStatistic.class,true);
//		return super.getListDomainByConditionAndOrder(sql, conditionMap,this.getTypeMap(MedicalRecipel.class),orderMap,true);
	}
	
	
	
	
//	@SuppressWarnings("unchecked")
//	@RequestMapping("/getBizListDomain.action")
//	public ListDomain<Object> getBizListDomain(@RequestBody(required=false) String body,HttpSession session){
//		String sql = dicService.getSqlByBizcode("medical_biz_statistic");
//		String userid = getUserid(session);
//		Map<String,Object> conditionMap = this.getBodyParam(body);
//		
//		
//		Map<String,String> paramMap = (Map<String, String>) conditionMap.get(ConstSysParam.CONDITION_MAP_KEY);
//		
//		String _outfield = "outhospitalat";
//		String _infield = "inhzospitalat";
//		
//		boolean _executeQry  = false;
//		//出院大于
//		String outGe = null;
//		//出院小于
//		String outLe = null;
//		//入院大于
//		String inGe = null;
//		//入院小于
//		String inLe = null;
//		String _keyDate_start = "outhospitalat_start";
//		String _keyDate_end = "outhospitalat_end";
//		if((paramMap.containsKey(_keyDate_start)) && (paramMap.containsKey(_keyDate_end))){
//			outGe= String.format(SysConfig.getConfig("dateGeTemplate"),_outfield ,paramMap.get(_keyDate_start));
//			inGe= String.format(SysConfig.getConfig("dateGeTemplate"),_infield ,paramMap.get(_keyDate_start));
//			
//			outLe = String.format(SysConfig.getConfig("dateLeTemplate"),_outfield ,paramMap.get(_keyDate_end));
//			inLe = String.format(SysConfig.getConfig("dateLeTemplate"),_infield ,paramMap.get(_keyDate_end));
//			_executeQry = true;
//		}		
//		
//		if(_executeQry){
//		String deptCondition = "";
//			if(!this.isSuperDept(userid,ConstSysParam.QUERY_ALL, "query_medical_all"))
//				deptCondition = String.format(" and doct_depart_code = '%1$s'", SysConfig.getUsr(userid).getDeptid().toString());
//			
//			if(paramMap.containsKey("doct_depart_name")){
//				String _tmpDept = paramMap.get("doct_depart_name");
//				if((_tmpDept !=null)&&(_tmpDept.trim().length()>0)){
//					_tmpDept = String.format(" and doct_depart_name = '%1$s'",_tmpDept.trim());
//					deptCondition = deptCondition ==""?_tmpDept: deptCondition + _tmpDept;
//				}
//			}
//			
//			if(paramMap.containsKey("doct_depart_name_like")){
//				String _tmpDept = paramMap.get("doct_depart_name_like");
//				if((_tmpDept !=null)&&(_tmpDept.trim().length()>0)){
//					_tmpDept = String.format(" and doct_depart_name like '%%%1$s%%'",_tmpDept.trim());
//					deptCondition = deptCondition ==""?_tmpDept: deptCondition + _tmpDept;
//				}
//			}
//			sql = String.format(sql, inGe,outLe,outGe,inLe,deptCondition);
//			conditionMap.put(ConstSysParam.CONDITION_MAP_KEY, new HashMap<String,Object>());
//			return super.getPagedClassListDomain(sql, conditionMap,MedicalInpatient.class,MedicalBizStatistic.class,true);
//		}else{
//			return new ListDomain<Object>();
//		}
//	}
	
	@SuppressWarnings("unchecked")
	@RequestMapping("/getBizListDomain.action")
	public ListDomain<MedicalStatistic> getBizListDomain(@RequestBody(required=false) String body,HttpSession session){
		String sql = dicService.getSqlByBizcode("medical_biz_statistic");
		String userid = getUserid(session);
		Map<String,Object> conditionMap = this.getBodyParam(body);
		
		
		Map<String,String> paramMap = (Map<String, String>) conditionMap.get(ConstSysParam.CONDITION_MAP_KEY);
			
		boolean _executeQry  = false;
		
		//出入院时间字段定义
		String _date_start = "outhospitalat_start";
		String _date_end = "outhospitalat_end";
		
		
		
		//判断出入院时间是否有效
		if((paramMap.containsKey(_date_start)) && (paramMap.containsKey(_date_end))){
			
			_executeQry = true;
		}		
		
		if(_executeQry){
		
			if(!this.isSuperDept(userid,ConstSysParam.QUERY_ALL, "query_medical_all"))
				paramMap.put("doct_depart_code", SysConfig.getUsr(userid).getDeptid().toString());		
			
			sql = StringUtil.formatSql( paramMap,sql);
			Integer[] pageParam = LongUtil.getPageParam(conditionMap);
			return super.getPagedListDomain(pageParam[0],pageParam[1], sql);
//			return super.getPagedClassListDomain(sql, conditionMap,MedicalInpatient.class,MedicalBizStatistic.class,true);
		}else{
			return new ListDomain<MedicalStatistic>();
		}
	}
	
	
	@RequestMapping("/getList.action")
	public List<MedicalStatistic> getList(@RequestParam(value="page",required=false) Integer page,
			@RequestParam(value="rows",required=false) Integer rows,
			@RequestParam(value="deptid",required=false) Integer deptid,
			@RequestParam(value="sort",required=false) String sort){		
		
		StringBuilder sb = new StringBuilder();
		String sql = "";
		if(deptid!=null){
			String whereCorse=String.format(sb.append("\"deptid\" = %1$d").toString(),deptid);
			sql = String.format(this.TW_SQL, this.tableName,whereCorse);
		}else{
			sql = String.format(this.T_SQL, this.tableName);
		}
		
		return super.getPagedList(page,rows,sql);
	}
	
	/**
	 * 获取业务数据统计值
	 * @param body
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping("/getChartStatistic.action")
	public Map<String,List<ChartDomain>> getChartStatistic(@RequestBody(required=false)String body,HttpSession session){
		
		Map<String,List<ChartDomain>> map = new HashMap<String,List<ChartDomain>>();
		String userid = getUserid(session);
		Map<String,Object> paramMap = this.getBodyParam(body);
		Map<String,String> conditonMap = (Map<String, String>) paramMap.get(ConstSysParam.CONDITION_MAP_KEY);
		Long bizCount = inService.getBizCount(body);
		
		conditonMap.put("inquiry_item_code", "5");
		List<ChartDomain> feeList = getChartAllInfo(conditonMap,bizCount,userid); 
		map.put("fee", feeList);
		
		conditonMap.put("inquiry_item_code", "6");
		List<ChartDomain> medicalList = getChartAllInfo(conditonMap,bizCount,userid); 
		map.put("drug", medicalList);
		
		conditonMap.put("inquiry_item_code", "7");
		List<ChartDomain> checkList = getChartAllInfo(conditonMap,bizCount,userid); 
		map.put("check", checkList);
		
		conditonMap.put("inquiry_item_code", "8");
//		List<ChartDomain> otherList = getChartAllInfo(conditonMap,bizCount,userid); 
		map.put("other", checkList);
		
		
		return  map;
	}
	
	private List<ChartDomain> getChartAllInfo(Map<String,String> paramMap,Long bizCount,String userid){
		
		List<ChartDomain> lists = new ArrayList<ChartDomain>();
		
		
		Long recipelCount = recipelService.getBizCount(paramMap);
		bizCount = bizCount ==null?0:bizCount;
		recipelCount = recipelCount ==null?0:recipelCount;
		
		ChartDomain bizDomain = new ChartDomain("正常人次","biz_summary",bizCount-recipelCount);
		lists.add(bizDomain);
		
		ChartDomain recipelDomain = new ChartDomain("异常人次","sumary_matter",recipelCount);
		lists.add(recipelDomain);
		return lists;
	}
	
	
	/**
	 * 根据用户id查找用户信息
	 * @param id	用户id
	 * @return 用户信息记录 
	 */
	@RequestMapping("/getOne.action")
	public MedicalStatistic getOne(@RequestParam(value="id",required=false) Long id){
		return super.getOne(id);
	}
	
	/**
	 * 根据用户唯一编码查找用户信息
	 * @param identify	用户唯一编码
	 * @return 用户信息记录
	 */
	@RequestMapping("/getOneByIdentify.action")
	public MedicalStatistic getOneByIdentify(@RequestParam(value="identify",required=false) String identify){	
		return super.getOneByIdentify(identify);
	}
	
	//MedicalStatistic
	/**
	 * 医疗服务统计信息异常数据
	 * @return
	 */	
	
	public List<MedicalStatistic> getMedicalstaticAbnormal(){		
		
		String sql = dicService.getSqlByBizcode("medical_static");	
		//sql = new String("select * from medical_anti_dose");
		sql = String.format(sql, DateUtil.getYestodayMonthDay()[2]);
		try {
			return super.getClassedAllList(sql, MedicalStatistic.class);
		} catch (DangerousOperatorException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		 	
		return null;
	}
	
}
